package com.lishe.lishe.lishe.module.excitation.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.lishe.base.common.adapter.CommonAdapter;
import com.lishe.base.common.adapter.MultiItemTypeAdapter;
import com.lishe.base.common.adapter.base.ViewHolder;
import com.lishe.base.common.adapter.wrapper.HeaderAndFooterWrapper;
import com.lishe.base.common.config.Constants;
import com.lishe.base.mvp.factory.CreatePresenter;
import com.lishe.base.viewpager.MZBannerView;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.GridDividerItemDecoration;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerLinearViewItemDecoration;
import com.lishe.base.common.base.AbstractFragment;
import com.lishe.lishe.lishe.bean.DianZanObject;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.excitation.activity.DianZanDetailsActivity;
import com.lishe.lishe.lishe.module.excitation.activity.DianzanShareActivity;
import com.lishe.lishe.lishe.module.excitation.activity.PersonExcitationActivity;
import com.lishe.lishe.lishe.module.excitation.activity.PersonReceiveAdmireActivity;
import com.lishe.lishe.lishe.module.excitation.activity.PersonReceiveGiftActivity;
import com.lishe.lishe.lishe.module.excitation.activity.PictureViewerActivity;
import com.lishe.lishe.lishe.module.excitation.bean.DianzanImgObject;
import com.lishe.lishe.lishe.module.excitation.bean.GiveLikeBannerResponse;
import com.lishe.lishe.lishe.module.excitation.bean.GiveLikeMessageResponse;
import com.lishe.lishe.lishe.module.excitation.bean.GiveLikeWallListResponse;
import com.lishe.lishe.lishe.module.excitation.dialog.ShowSendCommentDialog;
import com.lishe.lishe.lishe.module.excitation.dialog.ShowSendGiftDialog;
import com.lishe.lishe.lishe.module.excitation.interfaces.OnMessageChangeListener;
import com.lishe.lishe.lishe.module.excitation.presenter.GiveLikePresenter;
import com.lishe.lishe.lishe.module.excitation.presenter.GiveLikeWallView;
import com.lishe.lishe.lishe.module.mall.adapter.BannerImageHolder;
import com.lishe.lishe.lishe.module.mall.bean.GoodsItemsBean;
import com.lishe.lishe.lishe.module.mall.presenter.IndexPresenter;
import com.lishe.lishe.lishe.utils.BitmapUtils;
import com.lishe.lishe.lishe.utils.StringUtils;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.net.BaseProtocal;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * 标    题：点赞墙列表
 * 功能描述：DianZanWallFragment
 * 作    者：zouxx
 * 创建时间：2018/8/17
 */
@CreatePresenter(GiveLikePresenter.class)
public class GiveLikeWallFragment extends AbstractFragment<GiveLikeWallView, GiveLikePresenter> implements GiveLikeWallView {

    public static final int requestCode = 1;

    private int page = 1;
    private int totalPage = 1;
    private int pageSize = 20;
    private int clickPosition = -1;
    private LinearLayoutManager manager;
    private CommonAdapter<DianZanObject> adapter;
    private List<DianZanObject> dianzanList = new ArrayList<>();
    private List<GoodsItemsBean> banners = new ArrayList<>();
    private List<GiveLikeMessageResponse.DataBean.InfoBean> messages = new ArrayList();//通知消息

    private View view;
    private SmartRefreshLayout mSmartRefreshLayout;
    private RecyclerView recyclerView;
    private RelativeLayout empty, error;
    private TextView fresh;
    private ImageView back;
    private MZBannerView mzBannerView;
    private ViewFlipper viewFlipper;
    private View messageView;
    private HeaderAndFooterWrapper wrapper;
    private GridDividerItemDecoration decoration;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        decoration = new GridDividerItemDecoration(Utils.dp2px(5), false, false);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.activity_dianzan_wall, null);
            initView(view);
            view.setOnTouchListener(this);
            //设置刷新控件
            setSmartRefreshLayout();
        }
        return view;
    }

    private void initView(View view) {
        mSmartRefreshLayout = (SmartRefreshLayout) view.findViewById(R.id.refreshlayout);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        empty = view.findViewById(R.id.empty);
        error = view.findViewById(R.id.error);
        fresh = (TextView) view.findViewById(R.id.fresh);
        back = (ImageView) view.findViewById(R.id.back);

        initRecycleView();
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int firstPosition = manager.findFirstVisibleItemPosition();
                    if (firstPosition == 1 || firstPosition == 0) {
                        if (back.getVisibility() == View.GONE)
                            back.setVisibility(View.VISIBLE);
                    } else {
                        if (back.getVisibility() == View.VISIBLE)
                            back.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });//
        back.setOnClickListener(v -> getActivity().finish());
    }

    private void initRecycleView() {
        manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        recyclerView.addItemDecoration(new RecyclerLinearViewItemDecoration(Utils.dip2px(getActivity(), 10), false));
        adapter = new CommonAdapter<DianZanObject>(getActivity(), R.layout.item_give_like, dianzanList) {
            @Override
            protected void convert(ViewHolder holder, DianZanObject infoBean, int position) {
                bindData(holder, infoBean, position);
            }
        };
        recyclerView.setItemViewCacheSize(20);
        View bannerView = View.inflate(getActivity(), R.layout.index_banner_item, null);
        mzBannerView = bannerView.findViewById(R.id.index_banner);
        mzBannerView.setBannerPageClickListener((view, position1) -> {
            IndexPresenter.setOnClick(getActivity(), banners.get(position1));
        });
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                DianZanDetailsActivity.jump(GiveLikeWallFragment.this, dianzanList.get(position), requestCode);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        messageView = getActivity().getLayoutInflater().inflate(R.layout.item_viewfilper, null);
        viewFlipper = messageView.findViewById(R.id.viewfilper);
        viewFlipper.setVisibility(View.GONE);
        wrapper = new HeaderAndFooterWrapper(adapter);
        wrapper.addHeaderView(bannerView);
        wrapper.addHeaderView(messageView);
        recyclerView.setAdapter(wrapper);
    }

    private void bindData(ViewHolder holder, DianZanObject infoBean, int position) {
        ImageLoaderUtils.displayCircleImage(this, infoBean.getAvatarPath(), holder.getView(R.id.head_img), R.mipmap.head);
        RecyclerView recyclerView = holder.getView(R.id.image_recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        recyclerView.removeItemDecoration(decoration);
        recyclerView.addItemDecoration(decoration);
        recyclerView.setAdapter(new CommonAdapter<DianzanImgObject>(context, R.layout.item_round_image_view, infoBean.getImgList()) {
            @Override
            protected void convert(ViewHolder holder, DianzanImgObject dianzanImgObject, int position) {
                int width = (BitmapUtils.getDisplayWidth(getActivity()) - Utils.dip2px(context, 40)) / 3;
                ViewGroup.LayoutParams layoutParams = holder.getView(R.id.image_layout).getLayoutParams();
                layoutParams.width = width;
                layoutParams.height = width;
                ImageLoaderUtils.displayImage(getActivity(), dianzanImgObject.getImgUrl(), holder.getView(R.id.image_round), R.drawable.defalut_img);
                holder.itemView.setOnClickListener(v -> {
                    startActivity(new Intent(getActivity(), PictureViewerActivity.class)
                            .putExtra(Constants.PICTURE_VIEWER_POSITION, position).putExtra(Constants.PICTURE_VIEWER_IMAGES, infoBean.getImgList()));
                });
            }
        });
        holder.setText(R.id.name, infoBean.getEmpName());
        holder.setText(R.id.occupation, infoBean.getPosName());
        holder.setText(R.id.company, infoBean.getCreateUserName());
        holder.setText(R.id.content, StringUtils.utf8ToString(infoBean.getEventDesc()));
        holder.setText(R.id.note, infoBean.getActionName());
        holder.setVisible(R.id.lable, infoBean.getCreateUserType().equals("0"));
        holder.setText(R.id.forward, infoBean.getShareCount() == 0 ? "转发" : infoBean.getShareCount() + "");
        holder.setText(R.id.comment, infoBean.getCommentCount() == 0 ? "评论" : infoBean.getCommentCount() + "");
        holder.setText(R.id.gift, infoBean.getGiftCount() == 0 ? "礼物" : infoBean.getGiftCount() + "");
        holder.setText(R.id.dianzan, infoBean.getAdmiredCount() == 0 ? "鼓励" : infoBean.getAdmiredCount() + "");
        holder.setOnClickListener(R.id.head_img, v -> PersonExcitationActivity.jump(getActivity(), infoBean.getUserId()));
        holder.setOnClickListener(R.id.name, v -> PersonExcitationActivity.jump(getActivity(), infoBean.getUserId()));
        setListener(holder, infoBean, position);
    }

    private void setListener(ViewHolder holder, DianZanObject infoBean, int position) {
        holder.setOnClickListener(R.id.forward, v -> {
            DianzanShareActivity.jump(this, infoBean.getEventId(), infoBean.getAvatarPath(), infoBean.getEmpName(), infoBean.getEventDesc());
        });
        holder.setOnClickListener(R.id.company, v -> {
            if (!dianzanList.get(position).getCreateUserType().equals("0"))
                PersonExcitationActivity.jump(getActivity(), infoBean.getCreateUserId());
        });
        holder.setOnClickListener(R.id.gift, v -> {
            clickPosition = position;
            if (dianzanList.get(position).getUserId().equals(Globals.getExcatationUserId())) {
                //跳转到小礼列表
                PersonReceiveGiftActivity.jump(getActivity(), dianzanList.get(position).getEventId());
            } else {
                ShowSendGiftDialog.Builder builder = new ShowSendGiftDialog.Builder(getActivity());
                builder.setEventId(dianzanList.get(position).getEventId())
                        .setEventUserId(dianzanList.get(position).getUserId())
                        .setPointsType(1)
                        .setOnMessageChangeListener(listener);
                builder.show();
            }
        });
        holder.setOnClickListener(R.id.comment, v -> {
            clickPosition = position;
            ShowSendCommentDialog.Builder builder2 = new ShowSendCommentDialog.Builder(getActivity());
            builder2.setEventId(dianzanList.get(position).getEventId()).setOnMessageChangeListener(listener);
            builder2.show();
        });
        holder.setOnClickListener(R.id.dianzan, v -> {
            clickPosition = position;
            if (dianzanList.get(position).getUserId().equals(Globals.getExcatationUserId())) {
                //跳转到小礼列表
                PersonReceiveAdmireActivity.jump(getActivity(), dianzanList.get(position).getEventId());
            } else {
                if (infoBean.isFlag()) {
                    getMvpPresenter().cancelHitEvent(infoBean.getEventId());
                } else {
                    getMvpPresenter().hitEvent(infoBean.getEventId());
                }
            }
        });
    }

    private OnMessageChangeListener listener = new OnMessageChangeListener() {
        @Override
        public void messageChange(int type, int changeNum) {
            if (type == OnMessageChangeListener.GIFT_CHANGE_SUCCESS) {
                dianzanList.get(clickPosition).setGiftCount(dianzanList.get(clickPosition).getGiftCount() + changeNum);
            } else if (type == OnMessageChangeListener.COMMENT_CHANGE_SUCCESS) {
                dianzanList.get(clickPosition).setCommentCount(dianzanList.get(clickPosition).getCommentCount() + changeNum);
            }
            wrapper.notifyItemChanged(clickPosition, "");
        }
    };

    private void setSmartRefreshLayout() {
        mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
        mSmartRefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        mSmartRefreshLayout.setOnRefreshListener(refreshlayout -> {
            page = 1;
            getMvpPresenter().getGiveLikeList(page, pageSize);
            getMvpPresenter().getBannerList(Globals.getToken());
            mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
            if (!mSmartRefreshLayout.isEnableLoadmore())
                mSmartRefreshLayout.setEnableLoadmore(true);
        });

        mSmartRefreshLayout.setOnLoadmoreListener(refreshlayout -> {
            if (page <= totalPage) {
                getMvpPresenter().getGiveLikeList(page, pageSize);
                mSmartRefreshLayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
            } else {
                mSmartRefreshLayout.finishLoadmore(1000, true);
                mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getMvpPresenter().getMessageList(Globals.getToken());
    }

    @Override
    public void getGiveLikeList(GiveLikeWallListResponse response) {
        if (page == 1) {
            mSmartRefreshLayout.finishRefresh(true);
            dianzanList.clear();
        } else {
            mSmartRefreshLayout.finishLoadmore(true);
        }
        if (response.data != null) {
            totalPage = response.data.totalpage;
            if (response.data.info != null)
                dianzanList.addAll(response.data.info);
            if (dianzanList.size() > 0) {
                empty.setVisibility(View.GONE);
                wrapper.notifyDataSetChanged();
            } else {
                empty.setVisibility(View.VISIBLE);
                mSmartRefreshLayout.setEnableLoadmore(false);
            }
        }
        page = page + 1;
    }

    @Override
    public void getGiveLikeBanner(GiveLikeBannerResponse bannerResponse) {
        banners.clear();
        banners.addAll(bannerResponse.data);
        mzBannerView.setPages(banners, BannerImageHolder::new);
        if (banners.size() > 1) {
            mzBannerView.start();
        }
        mzBannerView.setIndicatorVisible(banners.size() > 1);
    }

    @Override
    public void getGiveLikeMessage(GiveLikeMessageResponse messageResponse) {
        messages.clear();
        if (messageResponse.data != null)
            messages.addAll(messageResponse.data.infoBean);
        if (messages == null || messages.size() == 0) {
            viewFlipper.setVisibility(View.GONE);
            return;
        } else {
            viewFlipper.setVisibility(View.VISIBLE);
        }
        addMessageView();
    }

    @Override
    public void hitEvent(BaseProtocal dataBean) {
        updateItem();
    }

    @Override
    public void cancelHitEvent(BaseProtocal dataBean) {
        updateItem();
    }

    private void updateItem() {
        if (dianzanList.get(clickPosition).isFlag()) {
            dianzanList.get(clickPosition).setFlag(false);
            dianzanList.get(clickPosition).setAdmiredCount(dianzanList.get(clickPosition).getAdmiredCount() - 1);
        } else {
            dianzanList.get(clickPosition).setFlag(true);
            dianzanList.get(clickPosition).setAdmiredCount(dianzanList.get(clickPosition).getAdmiredCount() + 1);
        }
        wrapper.notifyItemChanged(clickPosition, "");
    }

    private void addMessageView() {
        viewFlipper.setVisibility(View.VISIBLE);
        viewFlipper.removeAllViews();
        Log.e("消息数", messages.size() + "");
        for (int i = 0; i < messages.size(); i++) {
            final GiveLikeMessageResponse.DataBean.InfoBean myMessageObject = messages.get(i);
            View textlayour = getActivity().getLayoutInflater().inflate(R.layout.item_excition_message, null);
            final TextView text = textlayour.findViewById(R.id.text);
            text.setText(myMessageObject.messageContent);
            text.setOnClickListener(view -> DianZanDetailsActivity.jump(GiveLikeWallFragment.this,
                    myMessageObject.eventId, myMessageObject.id, requestCode, true));
            viewFlipper.addView(textlayour);
            if (messages.size() == 1) viewFlipper.stopFlipping();
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onFailure(int requestType, int errorCode, String errorMessage) {
        if (requestType == 1) {
            mSmartRefreshLayout.finishRefresh(1000, false);
            mSmartRefreshLayout.finishLoadmore(1000, false);
            fresh.setText("下拉刷新");
            if (dianzanList.size() == 0) {
                mSmartRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                error.setVisibility(View.VISIBLE);
            }
        }
        toast(R.string.network_or_server_exception);
    }

    @Override
    public void onLoading(String text) {
    }
    @Override
    public void onStop() {
        super.onStop();
        if (viewFlipper != null && viewFlipper.isFlipping() && messages.size() > 0) {
            viewFlipper.stopFlipping();
        }
    }
}